package org.bot.server.job;

import org.bot.server.flow.mapper.BotFlowMapper;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: 沧月
 * @Date: 2023/12/9 11:11
 * @Description: 描述
 */
@Component
public class QuartzJob {

    @Autowired
    BotFlowMapper flowMapper;

    // 创建调度器
    Scheduler scheduler;

    public QuartzJob() {
        try {
            scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.start();
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public void addJob(JobEntity jobEntity) {
        try {
            //检查当前任务是否已经存在
            JobKey jobKey = new JobKey(jobEntity.getJobKey(), jobEntity.getJobGroup());
            if (scheduler.checkExists(jobKey)) {
                return;
            }

            //添加任务
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(jobEntity.getTriggerKey(), jobEntity.getTriggerGroup())
                    .withSchedule(CronScheduleBuilder.cronSchedule(jobEntity.getCron()))
                    .build();

            //添加任务参数
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.putAll(jobEntity.getObjectMap());

            JobDetail job = JobBuilder.newJob(jobEntity.getJobClass())
                    .withIdentity(jobEntity.getJobKey(), jobEntity.getJobGroup())
                    .usingJobData(jobDataMap)
                    .build();
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteJob(JobEntity jobEntity) {
        JobKey jobKey = new JobKey(jobEntity.getJobKey(), jobEntity.getJobGroup());
        try {
            //检查当前任务是否已经存在
            if (scheduler.checkExists(jobKey)) {
                scheduler.deleteJob(jobKey);
            }

            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(jobEntity.getTriggerKey(), jobEntity.getTriggerGroup())
                    .build();
            if (scheduler.checkExists(trigger.getKey())) {
                scheduler.unscheduleJob(trigger.getKey());
            }
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }
}
